#include <iostream>
#include <cstdio>
#include <cstring>
#include <strings.h>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "user.hpp"
#include "my_pthread.hpp"

int sockfd = 0;

void Usage()
{
    printf("Using Warning , Please use the correct manual: \n ./server.cc ip port\n");
}

void *Sendmsg(void *argv)
{
    sockaddr_in *addr = (sockaddr_in *)argv;

    // 接受服务端的消息
    sockaddr_in rec;
    char buffer[1024];
    socklen_t len = sizeof(rec);

    std::string str;

    // 提示信息
    std::cout << "输入 \"online\" ,进行上线     输入 \"offline\" ,进行下线" << std::endl;
    std::cout << "输入 \"online\" ,进行上线     输入 \"offline\" ,进行下线" << std::endl;
    std::cout << "输入 \"online\" ,进行上线     输入 \"offline\" ,进行下线" << std::endl;

    while (true)
    {
        std::cout << "请输入 \"online\" 进行上线" << std::endl;
        getline(std::cin, str);
        if (str == "online")
        {
            sendto(sockfd, str.c_str(), str.size(), 0, (struct sockaddr *)addr, sizeof(*addr));
            std::cout << "上线成功! " << std::endl;
            break;
        }
    }

    // 发送消息
    while (true)
    {
        std::cout << "请输入消息: ";
        getline(std::cin, str);
        sendto(sockfd, str.c_str(), str.size(), 0, (struct sockaddr *)addr, sizeof(*addr));

        if (strcmp(str.c_str(), "offline") == 0)
        {
            break;
        }
    }
}

void *Recvmsg(void *argv)
{
    sockaddr_in rec;
    char buffer[1024];
    socklen_t len = sizeof(rec);

    // 发送消息
    while (true)
    {
        char buffer[1024];
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&rec, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer;
        }

        if (strcmp(buffer, "下线成功!\n") == 0)
        {
            break;
        }
    }
}

// ./client.cc 0.0.0.0 8080
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage();
        exit(1);
    }

    // 要向哪一个ip和端口号发送数据
    std::string ip = argv[1];
    uint16_t port = atoi(argv[2]);

    // 创建套接字
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        // 创建套接字失败
        std::cerr << "create socket error, errno: " << errno << " strerrno : " << strerror(errno) << std::endl;
        exit(1);
    }

    // sockaddr_in
    sockaddr_in addr;
    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());

    std::unique_ptr<Thread> send(new Thread("Thread 1", Sendmsg, (void *)(&addr)));
    std::unique_ptr<Thread> recv(new Thread("Thread 2", Recvmsg, (void *)(&addr)));

    send->Create();
    recv->Create();

    send->Join();
    recv->Join();

    return 0;
}